package routers

import (
	controllers "yun/Controllers"
	models "yun/Models"

	"github.com/gin-gonic/gin"
)

var db = models.DB

// 定义中间，验证token
func Middletoken() gin.HandlerFunc {
	return func(c *gin.Context) {
		access_token := c.Request.Header.Get("access-token")
		if access_token == "" {
			c.JSON(200, gin.H{
				"msg":  "请登录",
				"code": "1001",
			})
			c.Abort()
			return
		}
		userInfo, err := ValidateToken(access_token)
		if err != nil {
			c.JSON(200, gin.H{
				"msg":  "登录已过期",
				"code": "1001",
			})
			c.Abort()
			return
		}
		c.Set("userInfo", userInfo)
		c.Next()
	}
}

// 获取用户信息
func ValidateToken(token string) (interface{}, error) {
	user := models.User{}
	db.Where("token = ?", token).Find(&user)
	return user, nil
}
func Setuprouter(r *gin.Engine) {
	apirouter := r.Group("/api")
	{
		apirouter.POST("/adduser", controllers.ApiIndexController{}.Adduser)
		apirouter.POST("/login", controllers.ApiIndexController{}.Login)
		apirouter.POST("/usercenter", Middletoken(), controllers.ApiUserController{}.Usercenter)
		apirouter.POST("/useringoods", Middletoken(), controllers.ApiUserController{}.Useringoods)
		apirouter.POST("/goodslist", Middletoken(), controllers.ApiUserController{}.Goodslist)
		apirouter.POST("/delgoods", Middletoken(), controllers.ApiUserController{}.Delgoods)

	}
}
